﻿using Knlght.Mappings;
using Knlght.Model.Sys;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using EntityFramework.Extensions;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Knlght.Repository.DBContext
{
    public class EFDbContext : DbContext
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="nameOrConnectionString">连接字符串名</param>
        public EFDbContext(string nameOrConnectionString)
            : base(nameOrConnectionString)
        {
            // 不检查数据的映射
            Database.SetInitializer<EFDbContext>(null);
        }
        public EFDbContext() : base("default")
        {
            Database.SetInitializer<EFDbContext>(null);
            //数据库不存在时重新创建数据库
            //Database.SetInitializer<EFDbContext>(new CreateDatabaseIfNotExists<EFDbContext>());
            //每次启动应用程序时创建数据库
            //Database.SetInitializer<EFDbContext>(new DropCreateDatabaseAlways<EFDbContext>());
            //模型更改时重新创建数据库
            //Database.SetInitializer<EFDbContext>(new DropCreateDatabaseIfModelChanges<EFDbContext>());  
        }

        /// <summary>
        /// 添加数据库和实体的映射
        /// </summary>
        /// <param name="modelBuilder">将CLR类型映射到数据库</param>
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //表
            modelBuilder.Configurations.Add(new SysAdministratorsMapping());
            modelBuilder.Configurations.Add(new SysRoleInfoMapping());
            modelBuilder.Configurations.Add(new SysLogInfoMapping());
            modelBuilder.Configurations.Add(new SysNewsInfoMapping());
            modelBuilder.Configurations.Add(new SysNewsTypeMapping());
            modelBuilder.Configurations.Add(new SysLinkInfoMapping());
            modelBuilder.Configurations.Add(new SysSettingMapping());
            //视图               
        }


        public void FixEfProviderServicesProblem()
        {
            //The Entity Framework provider type 'System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer'  
            //for the 'System.Data.SqlClient' ADO.NET provider could not be loaded.   
            //Make sure the provider assembly is available to the running application.   
            //See http://go.microsoft.com/fwlink/?LinkId=260882 for more information.  

            var instance = System.Data.Entity.SqlServer.SqlProviderServices.Instance;
        }

    }
}
